package com.atshangluo.uncenterservice.controller;


import com.atshangluo.commonutils.JwtUtils;
import com.atshangluo.commonutils.R;
import com.atshangluo.servicebase.exceptionHandler.EduException;
import com.atshangluo.uncenterservice.entity.UcenterMember;
import com.atshangluo.uncenterservice.entity.vo.LoginVo;
import com.atshangluo.commonutils.Member;
import com.atshangluo.uncenterservice.entity.vo.RegisterVo;
import com.atshangluo.uncenterservice.service.UcenterMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author wsm
 * @since 2021-07-31
 */

@RestController
@RequestMapping("/api/member")
public class UcenterMemberController {


    @Autowired
    private UcenterMemberService memberService;


    @PostMapping("/login")
    public R login(@RequestBody LoginVo member){

        // 调用service里的login方法实现登陆，返回token值，使用Jwt生成

        String token = null;
        try {
            token = memberService.login(member);
        } catch (EduException e) {
            return R.error().message(e.getMsg());
        }

        return R.ok().data("token",token);
    }
    
    
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo member){

        try {
            memberService.register(member);
        }catch (EduException e){

            return R.error().message(e.getMsg());

        }




        return R.ok();
    }


    @GetMapping("/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){

        try{
          String id = JwtUtils.getMemberIdByJwtToken(request);
          UcenterMember member = memberService.getById(id);
          return R.ok().data("user",member);

        }catch (Exception e){
            throw new EduException(20001,"出错了");
        }
    }

    @GetMapping("/getUserInfo/user/{userId}")
    public com.atshangluo.commonutils.Member getUserInfo(@PathVariable("userId") String userId){

         UcenterMember member1 = memberService.getById(userId);

         Member member = new Member();

        BeanUtils.copyProperties(member1,member);

        return member;
    }

    @GetMapping("/register/{day}")
    public Integer registerCount(@PathVariable("day") String day){

        Integer count = memberService.countRegister(day);

        return count;
    }
}

